package com.example.myapplication.data.file;

import android.os.Bundle;
import android.util.Log;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplication.R;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class FileActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_file);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        try {

            File externalFilesDir = getExternalFilesDir(null);
            File file = new File(externalFilesDir, "b.txt");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write("Hello ExternalStorage".getBytes(StandardCharsets.UTF_8));
            fos.flush();

            FileInputStream fis = new FileInputStream(file);
            byte[] buf = new byte[1024];
            fis.read(buf);
            Log.d("FileActivity", "onCreate: " + new String(buf, StandardCharsets.UTF_8));
            fis.close();


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private void internalStorage() throws IOException {
        // 写文件
        /*FileOutputStream fos = openFileOutput("a.txt", MODE_APPEND);
        fos.write(new String("Hello World!").getBytes(StandardCharsets.UTF_8));
        fos.flush();
        fos.close();*/

        // 读文件
        FileInputStream fis = openFileInput("a.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
        byte[] buf = new byte[fis.available()];
        bis.read(buf);
        Log.d("FileActivity", "onCreate: " + new String(buf, StandardCharsets.UTF_8));
        bis.close();
        fis.close();
    }
}